package com.word;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.model.FieldsDocumentPart;
import org.apache.poi.hwpf.usermodel.Field;
import org.apache.poi.hwpf.usermodel.Fields;
import org.apache.poi.hwpf.usermodel.Range;

import com.artofsolving.jodconverter.DocumentConverter;
import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.converter.OpenOfficeDocumentConverter;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

public class ReadWriteAndDownloadDocServlet extends HttpServlet{
	
	public void doGet(HttpServletRequest request, 
			HttpServletResponse response) throws ServletException, IOException{
		doPost(request,response);
	}
	
	public void doPost(HttpServletRequest request, 
			HttpServletResponse response) throws ServletException, IOException{
		
		try {
			
			//读取word模板文件
			String s=getClass().getResource("/").getFile().toString();
			s=s.substring(0, s.lastIndexOf("/WEB-INF"));
			s=URLDecoder.decode(s,"utf-8");
			String fileDir = new File(s+"/doc").getCanonicalPath();
			System.out.println(fileDir);
			System.out.println(URLDecoder.decode(fileDir,"utf-8"));
			FileInputStream in = new FileInputStream(new File(fileDir+"/BASE.doc"));//base.doc为模板，通过替换模板内的内容实现表格输出
			HWPFDocument hdt = new HWPFDocument(in);
			Fields fields = hdt.getFields();
			Iterator<Field> it = fields.getFields(FieldsDocumentPart.MAIN).iterator();
			while(it.hasNext()){
				System.out.println(it.next().getType());
			}
			
			
			String fileName;
			
			//替换读取到的word模板内容的指定字段
			Range range = hdt.getRange();
			Map<String, String> map=new HashMap<String, String>();
			String stuId="19";//request.getSession().getAttribute("stuNum")
			Record res=Db.findFirst("select * from mediumterminspection where medium_student='"+stuId+"'");
			Record resInfo=Db.findFirst("select * from he_mid_print where student_id='"+stuId+"'");
			
			String q="";
			//fileName="中期检查表";
			fileName=resInfo.getStr("student_no")+resInfo.getStr("student_name")+"中期检查表";
			
			
			map.put("#dissTitle", resInfo.getStr("thesistitle_name"));
			map.put("#stuName", resInfo.getStr("student_name"));
			map.put("#stuNum", resInfo.getStr("student_no"));
			map.put("#stuClass",resInfo.getStr("student_xzb"));
			map.put("#stuLevel", resInfo.getStr("student_level"));
			map.put("#teacher", resInfo.getStr("teacher_name"));
			map.put("#nianji", resInfo.getStr("student_grade"));
			
			
			
			map.put("#space", res.getStr("medium_guideplace"));
			String workLoad=res.getStr("medium_workload");
			q="#Workload";
			if("A".equals(workLoad))
			{map.put(q+"1", "√");map.put(q+"2", "");map.put(q+"3", "");}
			else if("B".equals(workLoad))
			{map.put(q+"1", "");map.put(q+"2", "√");map.put(q+"3", "");}
			if("C".equals(workLoad))
			{map.put(q+"1", "");map.put(q+"2", "");map.put(q+"3", "√");}
			String difficult=res.getStr("medium_difficulty");
			
			q="#difficult";
			if("A".equals(difficult))
			{map.put(q+"1", "√");map.put(q+"2", "");map.put(q+"3", "");}
			else if("B".equals(difficult))
			{map.put(q+"1", "");map.put(q+"2", "√");map.put(q+"3", "");}
			if("C".equals(difficult))
			{map.put(q+"1", "");map.put(q+"2", "");map.put(q+"3", "√");}
			
			String richness=res.getStr("medium_richness");
			q="#richness";
			if("A".equals(richness))
			{map.put(q+"1", "√");map.put(q+"2", "");map.put(q+"3", "");}
			else if("B".equals(richness))
			{map.put(q+"1", "");map.put(q+"2", "√");map.put(q+"3", "");}
			if("C".equals(richness))
			{map.put(q+"1", "");map.put(q+"2", "");map.put(q+"3", "√");}
			
			String attitude=res.getStr("medium_attitude");
			q="#attitude";
			if("A".equals(attitude))
			{map.put(q+"1", "√");map.put(q+"2", "");map.put(q+"3", "");}
			else if("B".equals(attitude))
			{map.put(q+"1", "");map.put(q+"2", "√");map.put(q+"3", "");}
			if("C".equals(attitude))
			{map.put(q+"1", "");map.put(q+"2", "");map.put(q+"3", "√");}
			
			
			
			map.put("#medium_readiness", res.getStr("medium_readiness"));
			map.put("#medium_independent", res.getStr("medium_independent"));
			map.put("#medium_progress", res.getStr("medium_progress"));
			map.put("#medium_checkway", res.getStr("medium_checkway"));
			map.put("#medium_guidetimes", res.getStr("medium_guidetimes"));
			
			//转换
			for (Map.Entry<String,String> entry:map.entrySet()) {
				range.replaceText(entry.getKey(),entry.getValue());
			}
			
			
			//暂存
			BufferedOutputStream bos = null;  
	        FileOutputStream fos = null;  
	        File tempFile = null;
            tempFile = new File(s+"/doc/fillTempFile.doc");  
            fos = new FileOutputStream(tempFile);  
            bos = new BufferedOutputStream(fos);  
            hdt.write(fos);
			
			
			//转换成pdf
			/*File pdfFile,sourceFile;
			pdfFile =new File(s+"/doc/"+fileName+".pdf");
			sourceFile=tempFile;
			if(pdfFile.exists())
			{
				pdfFile.delete();
			}
			OpenOfficeConnection connection =new SocketOpenOfficeConnection(8100);
			connection.connect();
			DocumentConverter converter=new OpenOfficeDocumentConverter(connection);
			converter.convert(sourceFile, pdfFile);
			pdfFile.createNewFile();
			connection.disconnect();
			System.out.println("转换为pdf格式 路径"+pdfFile.getParent());
			tempFile.delete();*/
			
			//输出word内容文件流，提供下载
			response.reset();
            response.setContentType("application/x-msdownload");
            response.addHeader("Content-Disposition", "attachment; filename=\""+new String((fileName+".doc").getBytes("utf-8"),"iso8859-1")+"\"");
			ByteArrayOutputStream ostream = new ByteArrayOutputStream();
			ServletOutputStream servletOS = response.getOutputStream();
			hdt.write(ostream);
			servletOS.write(ostream.toByteArray());
			servletOS.flush();
			servletOS.close();
			
			
            // 取得文件的后缀名。
            //String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();

            // 以流的形式下载文件。
           /* InputStream fis = new BufferedInputStream(new FileInputStream(pdfFile));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            // 设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename=\""+new String((fileName+".pdf").getBytes("utf-8"),"iso8859-1")+"\"");
            response.addHeader("Content-Length", "" + pdfFile.length());
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            toClient.write(buffer);
            toClient.flush();
            toClient.close();*/
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			
		}
	}

}
